/**
 * 用户相关服务
 */
import util from 'utils/util.js';
import api from 'utils/config/api.js';
import store from '../store/index.js';
import storage from 'utils/storage.js'

/**
 * Promise封装wx.checkSession
 */
function checkSession() {
	return new Promise(function(resolve, reject) {
		uni.checkSession({
			success: function() {
				resolve(true);
			},
			fail: function(err) {
				console.log(err)
				reject(false);
			}
		})
	});
}

/**
 * Promise封装wx.login
 */
function login() {
	return new Promise(function(resolve, reject) {
		uni.login({
			success: function(res) {
				console.log(res);
				if (res.code) {
					resolve(res);
				} else {
					reject(res);
				}
			},
			fail: function(err) {
				reject(err);
			}
		});
	});
}

/**
 * 调用微信登录
 */
function loginByWeixin(userInfo) {
	let shareUserId = storage.getStorageSync('shareUserId');
	if (!shareUserId || shareUserId == 'undefined') {
		shareUserId = 1;
	}
	return new Promise(function(resolve, reject) {
		return login().then((res) => {
			//登录远程服务器
			util.request(api.api.AuthLoginByWeixin, {
				code: res.code,
				userInfo: userInfo,
				shareUserId: shareUserId
			}, 'POST').then(res => {
				if (res.errno === 0) {
					//存储用户信息
					storage.setStorageSync('userInfo', res.data.userInfo);
					store.state.user = res.data.userInfo;
					store.state.hasLogin = true;
					storage.setStorageSync('token', res.data.token);

					resolve(res);
				} else {
					reject(res);
				}
			}).catch((err) => {
				reject(err);
			});
		}).catch((err) => {
			reject(err);
		})
	});
}

/**
 * 判断用户是否登录
 */
function checkLogin() {
	return new Promise(function(resolve, reject) {
		console.log(storage.getStorageSync('userInfo'))
		 console.log(storage.getStorageSync('token'))
		  
		if (storage.getStorageSync('userInfo') && storage.getStorageSync('token')) {
			checkSession().then(() => {
				console.log(store.state);
				store.state.user = storage.getStorageSync('userInfo');
				store.state.hasLogin = true;
				resolve(true);
			}).catch(() => {
				reject(false);
			});
		} else {
			reject(false);
		}
	});
}

export default {
	loginByWeixin,
	checkLogin,
};
